package com.woniuxy.wd.dao.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

public class MyDAOTemplet implements DAOInterface {
	
	private Connection con;

	private String tableName; //表名
	private String basePackage = "com.woniuxy.wd.dao.po";

	public void setCon(Connection con) {
		this.con = con;
	}
	
	public Connection getCon() {
		return con;
	}

	public void setTableName(String tableName){
		this.tableName = tableName;
	}
	
	@Override
	public Object findById(int id) {
		Object obj = null;
		StringBuffer sql = new StringBuffer("SELECT * FROM ");
		sql.append(tableName);  //字符串拼接,增加表名
		sql.append(" WHERE id = ?"); //增加条件
		try {
			//预编译,sql语句
			PreparedStatement ps = con.prepareStatement(sql.toString());
			ps.setInt(1, id);
			ResultSet rs = ps.executeQuery();
			//路径+表名转换大写
			String poName = basePackage + "." + tableName.substring(0, 1).toUpperCase() + tableName.substring(1);
			
			while(rs.next()){
				
				Class clzz = Class.forName(poName);
				obj = clzz.newInstance();
				//遍历字段,然后来转换大写,来获取方法名
				Field[] fields = clzz.getDeclaredFields();
				for(Field f : fields){
					String methodName = "set" + f.getName().substring(0,1).toUpperCase() + f.getName().substring(1);
					//获取方法名和类型
					Method m = clzz.getMethod(methodName, f.getType());
					//调用方法
					m.invoke(obj, rs.getObject(f.getName()));
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return obj;
	}

	@Override
	public Object findByFK(int fk) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List findByProperties(String name) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List findByProperties(String... parms) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List findByProperties(String[] args0, String[] args1) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int update(String[] args0, String[] args1) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int save(Object t) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public List executeQuery(String sql) {
		// TODO Auto-generated method stub
		return null;
	}

}
